<?php

namespace app\api\controller\wanlshop;

use app\common\controller\Api;
use app\admin\model\wanlshop\UserShare;
use app\admin\model\wanlshop\ShareOrder;
use app\admin\model\wanlshop\Share as shareModel;
use app\api\model\wanlshop\Order;

class Share extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function info()
    {
        $user_id = $this->auth->id;
        $user = \app\common\model\User::field(['id', 'avatar', 'username', 'nickname'])->find(['id' => $user_id]);
        $share = shareModel::where('user_id', $user_id)->find();
        if ($share) {
            $share['total'] = bcadd($share['waitting'] ?? 0, $share['amount'] ?? 0, 2);
            $share['bi'] = ShareOrder::where(['parent_share_id' => $share['id'] ?? 0, 'status' => 1])->count();
        }
        $this->success('返回成功', [
            'user' => $user,
            'share' => $share
        ]);
    }

    public function apply()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $model = shareModel::where('user_id', $this->auth->id)->find();
            $level = 1;
            if ($model) {
                if ($model['status'] != 2) {
                    $this->error(__('不能重复申请'));
                }
            } else {
                if (!empty($data['data']['inv_code'])) {
                    $exist = shareModel::where('code', $data['data']['inv_code'])->find();
                    if (!$exist) {
                        $this->error(__('邀请码不存在'));
                    }
                    $level = 2;
                }
                $model = new shareModel();
            }
            $model->user_id = $this->auth->id;
            $model->realname = $data['data']['realname'];
            $model->account = $data['data']['account'];
            $model->address = $data['data']['address'];
            $model->level = $level;
            $model->id_frontend = $data['data']['id_frontend'];
            $model->id_backend = $data['data']['id_backend'];
            $model->mobile = $data['data']['mobile'];
            $model->id_number = $data['data']['id_number'];
            $model->parent_id = !empty($exist) ? $exist['id'] : 0;
            $model->status = 0;
            $model->save();
            $this->success('申请成功');
        }
        $this->error(__('非法请求'));
    }

    public function list()
    {
        $id = $this->request->get('id', 0);
        $size = $this->request->get('pageSize', 10);
        $model = shareModel::where('user_id', $this->auth->id)->find();
        $target = $id ?: $model['id'];
        $list = ShareOrder::where(['parent_share_id' => $target])
            ->with(['share', 'user'])
            ->order('id', 'desc')
            ->paginate($size)
            ->each(function ($item) {
                $item->buy_text = Order::getOrderType($item->order_id);
            });
        $list = $list->toArray();
        foreach ($list['data'] as $key => $item) {
            if (!$item['user']) {
                unset($list['data'][$key]);
            }
            $order = Order::find($item['order_id']);
            if (in_array($order['state'], [1, 5, 7, 8, 9, 10])) {
                unset($list['data'][$key]);
            }
        }
        $list['data'] = array_values($list['data']);
        $this->success('获取成功', $list);
    }

    public function partner()
    {
        $uid = $this->auth->id;
        $share = shareModel::where('user_id', $uid)->find();
        $size = $this->request->get('pageSize');
        $uids = shareModel::where('parent_id', $share['id'])->column('user_id');
        $uids = $uids ? array_merge($uids, [$share['user_id']]) : [$share['user_id']];
        $list = UserShare::where('parent_id', 'in', $uids)
            ->with([
                'user' => function ($query) {
                    $query->field(['id', 'avatar', 'nickname', 'username']);
                }
            ])
            ->order('id', 'desc')
            ->paginate($size);
        $res = [];
        if ($list) {
            foreach ($list as &$item) {
                $share = shareModel::where('user_id', $item['parent_id'])->find();
                $item['share'] = $share;
                $item['level'] = $share['level'];
                $res[] = $item;/*
                $children = UserShare::where('parent_id', $item['user_id'])
                    ->with(['user' => function ($query) {
                        $query->field(['id', 'avatar', 'nickname', 'username']);
                    }])
                    ->order('id', 'desc')
                    ->select();
                if ($children) {
                    foreach ($children as $item2) {
                        $share = shareModel::where('user_id', $item2['parent_id'])->find();
                        $item2['share'] = $share;
                        $item2['level'] = $share['level'];
                        $res[] = $item2;
                    }
                }*/
            }
        }
        $this->success('获取成功', array_values(array_unique(array_column($res, null, 'id'))));
    }

    public function children()
    {
        $uid = $this->auth->id;
        $size = $this->request->get('pageSize');
        $info = shareModel::where('user_id', $uid)->find();
        $this->success('获取成功', array_values($this->getChildren($info['id'])));
    }

    private function getChildren($id, &$res = [])
    {
        $s = shareModel::where('parent_id', $id)->with('user')->order('id', 'desc')->select();
        if ($s) {
            foreach ($s as $item) {
                if (!$item->user) {
                    continue;
                }
                $res[] = $item;
                $this->getChildren($item['id'], $res);
            }
        }
        return $res;
    }

    public function order_list()
    {
        $uid = $this->auth->id;
        $size = $this->request->get('pageSize');
        $info = shareModel::where('user_id', $uid)->find();
        $children = array_values($this->getChildren($info['id']));
        $list = [];
        if ($children) {
            $uids = array_column($children, 'user_id');
        } else {
            $uids = UserShare::where('parent_id', $uid)->column('user_id');
        }
        $list = Order::where('user_id', 'in', $uids)
            ->with(['user', 'pay', 'realstore'])
            ->order('createtime', 'desc')
            ->paginate($size)
            ->each(function ($item) {
                $item->buy_text = Order::getOrderType($item->id);
                $item->shareOrder = ShareOrder::where('order_id', $item->id)->with('share')->find();
            });
        $this->success('', $list);
    }
}